package com.xw.controller.callbackcontroller;

import cn.hutool.core.util.NumberUtil;
import com.xw.dao.*;
import com.xw.model.*;
import com.xw.sdk.wechat.WXPayUtil;
import com.xw.util.AppUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/weChatCallBack")
public class WeChatCallBackController {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrdersItemMapper ordersItemMapper;
    @Autowired
    private VideosMapper videosMapper;
    @Autowired
    private PlatformBillMapper platformBillMapper;
    @Autowired
    private BasicSetMapper basicSetMapper;
    @Autowired
    private BuyVideosMapper buyVideosMapper;
    @Autowired
    private TopupMapper topupMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserBillMapper userBillMapper;

    @RequestMapping(value = "/toTopup",produces="text/html;charset=utf-8")
    @ResponseBody
    public String toTopup(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String,String> return_data = new HashMap<String,String>();

        ServletInputStream instream = request.getInputStream();
        StringBuffer sb = new StringBuffer();
        int len = -1;
        byte[] buffer = new byte[1024];

        while((len = instream.read(buffer)) != -1){
            sb.append(new String(buffer,0,len));
        }
        instream.close();

        Map<String, String> map = WXPayUtil.xmlToMap(sb.toString());
        //业务结果 result_code SUCCESS
        //此字段是通信标识，非交易标识，交易是否成功需要查看result_code来判断 SUCCESS/FAIL
        if ("SUCCESS".equals(map.get("return_code")) && "SUCCESS".equals(map.get("result_code"))) {
            //商户生成的订单号 自己生成的
            String out_trade_no = map.get("out_trade_no");
            String transactionId = map.get("transaction_id");

            Boolean flag = false;

            Topup model = new Topup();
            model.setOrdersId(out_trade_no);

            Topup topup = topupMapper.selectOne(model);
            //充值状态 0.未支付 1.已支付
            topup.setTopupStatus(1);
            topup.setTransactionId(transactionId);
            topupMapper.updateByPrimaryKeySelective(topup);

            //添加账户余额
            User user = userMapper.selectByPrimaryKey(topup.getUserId());
            if (user != null){
                user.setBalance(NumberUtil.add(user.getBalance(),topup.getMoney()));
                userMapper.updateByPrimaryKeySelective(user);
            }


            flag = true;
            if(flag){
                //修改订单成功之后通知微信，防止微信重复调用
                return_data.put("return_code", "SUCCESS");
                return_data.put("return_msg", "OK");
                return WXPayUtil.mapToXml(return_data);
            }else{
                return_data.put("return_code", "FAIL");
                return WXPayUtil.mapToXml(return_data);
            }

        } else {
            //修改订单成功之后通知微信，防止微信重复调用
            return_data.put("return_code", "FAIL");
            return WXPayUtil.mapToXml(return_data);
        }
    }

    /**
     * 支付订单
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/payOrders",produces="text/html;charset=utf-8")
    @ResponseBody
    public String payOrders(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String,String> return_data = new HashMap<String,String>();

        ServletInputStream instream = request.getInputStream();
        StringBuffer sb = new StringBuffer();
        int len = -1;
        byte[] buffer = new byte[1024];

        while((len = instream.read(buffer)) != -1){
            sb.append(new String(buffer,0,len));
        }
        instream.close();

        Map<String, String> map = WXPayUtil.xmlToMap(sb.toString());
        //业务结果 result_code SUCCESS
        //此字段是通信标识，非交易标识，交易是否成功需要查看result_code来判断 SUCCESS/FAIL
        if ("SUCCESS".equals(map.get("return_code")) && "SUCCESS".equals(map.get("result_code"))) {
            //商户生成的订单号 自己生成的
            String out_trade_no = map.get("out_trade_no");
            String transaction_id = map.get("transaction_id");

            Boolean flag = false;

            Orders model = new Orders();
            model.setOrderNo(out_trade_no);
            Orders orders = ordersMapper.selectOne(model);
            //订单状态: 0-已取消， 1-待付款，2-已付款(已完成)
            orders.setStatus(2);
            orders.setPaymentTime(new Date());
            ordersMapper.updateByPrimaryKeySelective(orders);

            //更新销量 根据订单查询购买的哪个视频
            List<String> videosIdList = ordersItemMapper.findVideosIdByOrdersNo(out_trade_no);
            if (videosIdList.size() > 0){
                for (String s : videosIdList) {
                    Videos videos = videosMapper.selectByPrimaryKey(s);
                    videos.setSaleCount(videos.getSaleCount() + 1);
                    videosMapper.updateByPrimaryKeySelective(videos);

                    //添加购买视频记录
                    BuyVideos buyVideos = new BuyVideos();
                    buyVideos.setId(AppUtil.uuid());
                    buyVideos.setUserId(orders.getUserId());
                    buyVideos.setVideosId(s);
                    buyVideosMapper.insertSelective(buyVideos);

                    //付款之后将一部分抽成记录到账单表中
                    BasicSet basicSet = basicSetMapper.selectAll().get(0);
                    //抽成的钱
                    double mul = NumberUtil.mul(basicSet.getPercent(), orders.getPayment());
                    PlatformBill bill = new PlatformBill();
                    bill.setId(AppUtil.uuid());
                    bill.setBillType(0);
                    bill.setMoney(mul);
                    bill.setOrdersNo(out_trade_no);
                    bill.setCreateTime(new Date());
                    platformBillMapper.insertSelective(bill);

                    //给视频发布者钱，90%
                    double sub = NumberUtil.sub(orders.getPayment(), (Double) mul);
                    String videosUserId = videos.getUserId();
                    User videosUser = userMapper.selectByPrimaryKey(videosUserId);
                    videosUser.setBalance(NumberUtil.add(videosUser.getBalance(),(Double) sub));
                    userMapper.updateByPrimaryKeySelective(videosUser);

                    //添加用户账单
                    UserBill userBill = new UserBill();
                    userBill.setId(AppUtil.uuid());
                    userBill.setUserId(videosUserId);
                    userBill.setBillTitle("视频收入-" + videos.getVideoName());
                    //设置账单类型 0. 加 1.减
                    userBill.setBillType(0);
                    userBill.setMoney(sub);
                    userBill.setCreateTime(new Date());
                    userBill.setFromUserId("0");
                    userBill.setFlag(2);
                    //0.未付款 1.已付款
                    userBill.setPayStatus(1);
                    //0.余额 1.支付宝 2.微信
                    userBill.setPayType(2);
                    userBill.setOrdersNo(out_trade_no);
                    userBill.setTransactionId(transaction_id);
                    userBillMapper.insertSelective(userBill);
                }
            }

            flag = true;
            if(flag){
                //修改订单成功之后通知微信，防止微信重复调用
                return_data.put("return_code", "SUCCESS");
                return_data.put("return_msg", "OK");
                return WXPayUtil.mapToXml(return_data);
            }else{
                return_data.put("return_code", "FAIL");
                return WXPayUtil.mapToXml(return_data);
            }

        } else {
            //修改订单成功之后通知微信，防止微信重复调用
            return_data.put("return_code", "FAIL");
            return WXPayUtil.mapToXml(return_data);
        }
    }

    /**
     * 微信回调案例
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/test",produces="text/html;charset=utf-8")
    @ResponseBody
    public String test(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String,String> return_data = new HashMap<String,String>();

        ServletInputStream instream = request.getInputStream();
        StringBuffer sb = new StringBuffer();
        int len = -1;
        byte[] buffer = new byte[1024];

        while((len = instream.read(buffer)) != -1){
            sb.append(new String(buffer,0,len));
        }
        instream.close();

        //将微信返回的数据解析成map
        //map返回的参数案例
        //        {
        //           "appid": "wx4c36afc61bb54516",
        //           "bank_type": "CFT",
        //           "cash_fee": "1",
        //           "fee_type": "CNY",
        //           "is_subscribe": "N",
        //           "mch_id": "1503698631",
        //           "nonce_str": "FE18C39734C0496EA5B4A302C73D734F",
        //           "openid": "oiKat0ecjo0ZcrxNSmLr5LjMSywI",
        //           "out_trade_no": "201807021036198134",
        //           "result_code": "SUCCESS",
        //           "return_code": "SUCCESS",
        //           "sign": "3EFEBE2558C41D82DF6D267CA87E3644",
        //           "time_end": "20180702103627",
        //           "total_fee": "1",  支付金额
        //           "trade_type": "APP",
        //           "transaction_id": "4200000131201807026102676889"
        //        }
        Map<String, String> map = WXPayUtil.xmlToMap(sb.toString());
        //业务结果 result_code SUCCESS
        //此字段是通信标识，非交易标识，交易是否成功需要查看result_code来判断 SUCCESS/FAIL
        if ("SUCCESS".equals(map.get("return_code")) && "SUCCESS".equals(map.get("result_code"))) {
            //商户生成的订单号 自己生成的
            String out_trade_no = map.get("out_trade_no");

            if(true){
                //修改订单成功之后通知微信，防止微信重复调用
                return_data.put("return_code", "SUCCESS");
                return_data.put("return_msg", "OK");
                return WXPayUtil.mapToXml(return_data);
            }else{
                return_data.put("return_code", "FAIL");
                return WXPayUtil.mapToXml(return_data);
            }

        } else {
            //修改订单成功之后通知微信，防止微信重复调用
            return_data.put("return_code", "FAIL");
            return WXPayUtil.mapToXml(return_data);
        }
    }
}
